//
// Created by tang on 3/6/23.
//

#include "pi_http_service.hpp"

#include <cpr/cpr.h>
#include "cpr/accept_encoding.h"

class cpr_get final : public IHttpService::IHttpGet {
    cpr::Session session;
    cpr::Header  header;
    cpr::Parameters parameters;
public:
    cpr_get(const std::string &base_url) {
        session.SetUrl (base_url);
    }
    ~cpr_get() override {

    }

    IHttpGet *add_header (const std::string &key, const std::string &value) override
    {
        header.emplace (std::pair{key, value});
        return this;
    }
    IHttpGet *add_param (const std::string &key, const std::string &value) override
    {
        parameters.Add ({key, value});
        return this;
    }
    IHttpGet *ssl (bool on) override
    {
        session.SetVerifySsl (cpr::VerifySsl(on));
        return this;
    }
    std::string perform () override
    {
        std::string result;

        session.SetHeader (header);
        session.SetParameters (parameters);
        session.SetAcceptEncoding(cpr::AcceptEncoding{
            cpr::AcceptEncodingMethods::identity,
            cpr::AcceptEncodingMethods::deflate,
            cpr::AcceptEncodingMethods::gzip,
            cpr::AcceptEncodingMethods::zlib,
            });
        cpr::Response response = session.Get();
        // L_INFO("http get: %s", session.GetFullRequestUrl().c_str());
        if (response.status_code == 200) {
            result = response.text;
        } else {
            L_ERROR ("HTTP REQUEST %s CODE %d", response.url.c_str(), response.status_code);
        }
        return result;
    }
};

pi_http_service::pi_http_service () {

}

pi_http_service::~pi_http_service () {

}

IHttpService::HttpGetPtr pi_http_service::new_get (const std::string &base_url)
{
    return std::make_unique<cpr_get>(base_url);
}
